<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddPage">添加商品</el-button>
        </el-col>
      </el-row>
      <!--表格区域-->
      <el-table :data="goodsList" height="700" border stripe v-loading="loading" element-loading-text="拼命加载中">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格" width="95px" prop="goods_price">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goods_price"
                      v-if="scope.row.showGoods_price"
                      @blur="GoodsPriceBlur(scope.row)"
                      ref="GoodsPriceInput"></el-input>
            <span v-text="scope.row.goods_price" v-else @click="showGoods_priceClick(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" width="95px" prop="goods_number">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.goods_number"
                      v-if="scope.row.showGoods_number"
                      @blur="GoodsNumberBlur(scope.row)"
                      ref="GoodsNumberInput"></el-input>
            <span v-text="scope.row.goods_number" v-else @click="showGoods_numberClick(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column label="商品重量" width="95px" prop="goods_weight"></el-table-column>
        <el-table-column label="商品状态" width="95px" prop="goods_state"></el-table-column>
        <el-table-column label="热销品数量" width="95px" prop="hot_mumber"></el-table-column>
        <el-table-column label="创建时间" prop="add_time">
          <template slot-scope="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="upd_time">
          <template slot-scope="scope">
            {{ scope.row.upd_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scope.row.goods_id)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"
                       @click="removeById(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
  </div>
</template>

<script>
  export default {
    name: 'List',
    data() {
      return {
        // 查询参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 10
        },
        // 商品列表
        goodsList: [],
        // 加载项
        loading: true,
        // 总数据条数
        total: 0,
        // 商品价格输入框显示切换
        showGoods_price: false,
        // 商品价格
        price: 0,
        // 商品数量
        number: 0
      }
    },
    created() {
      document.addEventListener('keydown', (e) => {
        const key = window.event.keyCode
        if (key === 13) {
          this.getGoodsList()
        }
      })
      this.getGoodsList()
    },
    methods: {
      // 获取商品数据
      async getGoodsList() {
        const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品列表失败!')
        }
        this.$message.success('获取商品列表成功!')
        res.data.goods.forEach(item => {
          item.showGoods_price = false
          item.showGoods_number = false
        })
        setTimeout(() => {
          this.loading = false
        }, 1000)
        this.goodsList = res.data.goods
        this.total = res.data.total
      },
      // 监听pageSize改变事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getGoodsList()
      },
      // 监听pagenum改变事件
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getGoodsList()
      },
      // 根据Id删除商品
      async removeById(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已经取消删除!')
        }
        const { data: res } = await this.$http.delete(`goods/${id}`)

        if (res.meta.status !== 200) {
          return this.$message.error('删除商品失败!')
        }
        this.$message.success(res.meta.msg)
        this.queryInfo.query = ''
        this.getGoodsList()
      },
      // 商品价格显示切换
      showGoods_priceClick(row) {
        this.price = row.goods_price
        row.showGoods_price = true
        this.$nextTick(_ => {
          this.$refs.GoodsPriceInput.$refs.input.focus()
        })
      },
      //  商品价格失去焦点事件
      GoodsPriceBlur(row) {
        const regx = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,2})$)|^(([1-9]+)$)/
        if (row.goods_price === '' || row.goods_price === null || row.goods_price === undefined) {
          this.$nextTick(_ => {
            this.$refs.GoodsPriceInput.$refs.input.focus()
          })
          row.goods_price = this.price
          return this.$message.error('商品价格不能为空!')
        }
        if (!regx.test(row.goods_price)) {
          this.$nextTick(_ => {
            this.$refs.GoodsPriceInput.$refs.input.focus()
          })
          row.goods_price = this.price
          return this.$message.error('商品价格只能是数字最大2位小数点!')
        }
        row.showGoods_price = false
      },
      // 商品价格点击事件
      showGoods_numberClick(row) {
        row.showGoods_number = true
        this.$nextTick(_ => {
          this.$refs.GoodsNumberInput.$refs.input.focus()
        })
      },
      // 商品数量失去焦点事件
      GoodsNumberBlur(row) {
       row.showGoods_number = false
      },
      // 跳转添加商品页面
      goAddPage() {
        this.$router.push('/goods/add')
      },
      // 跳转编辑修改商品页面
      edit(id) {
        this.$router.push({ path: '/goods/edit', query: { key: id } })
      }
    }
  }
</script>

<style lang="less" scoped>
</style>
